package com.ruoyi.sys.lonin.util;

import com.alibaba.fastjson.JSON;
import com.ruoyi.sys.lonin.entity.CodeToken;
import com.ruoyi.sys.lonin.entity.WeChatPerson;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 微信登录授权帮助类
 * @description: TODO
 * @author js
 * @date 2022-05-27 19:30:25
 * @return * @return: 返回用户信息
 * @throws
 * @version 1.0
 */
public class WxUtils {
    public static WeChatPerson getLogin(String  appid, String secret, String code) throws Exception{
        HttpClient httpclient =  HttpClients.createDefault();

        //使用code交换token
        String smsUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ appid +"&SECRET="+ secret + "&code=" + code + "&grant_type=authorization_code";
        HttpGet httpGet = new HttpGet(smsUrl);
        String strResult = "";
        HttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            strResult = EntityUtils.toString(response
                    .getEntity(),"UTF-8");
        }
        //解析数据
        CodeToken codeToken = JSON.parseObject(strResult, CodeToken.class);

        //使用token拉取用户信息
        String smsUrl1="https://api.weixin.qq.com/sns/userinfo?access_token="+codeToken.getAccess_token()+"&openid="+codeToken.getOpenid()+"&lang=zh_CN";
        HttpGet httpGet1 = new HttpGet(smsUrl1);
        String strResult1 = "";
        HttpResponse response1 = httpclient.execute(httpGet1);
        if (response.getStatusLine().getStatusCode() == 200) {
            strResult1 = EntityUtils.toString(response1
                    .getEntity(),"UTF-8");
        }
        //解析数据
        WeChatPerson weChatPerson = JSON.parseObject(strResult1, WeChatPerson.class);
        return weChatPerson;
    }
}

